package com.qf.cx.simplenms.webservice.controller;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.qf.cx.simplenms.persist.entity.TopicEntity;
import com.qf.cx.simplenms.persist.service.api.TopicService;
import com.qf.cx.simplenms.webservice.model.Topic;

@RestController
@RequestMapping(path = "/topics")
public class TopicController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private TopicService topicService;

	@RequestMapping(method = RequestMethod.GET)
	public List<Topic> getTopics() {
		List<TopicEntity> topics = topicService.getTopics();
		List<Topic> list = new ArrayList<>();
		topics.forEach(t -> list.add(Topic.from(t)));
		return list;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void addTopics(@RequestBody List<Topic> topics) {
		logger.debug("add topics {}", topics);
		List<TopicEntity> topicEntities = new ArrayList<>(topics.size());
		topics.forEach(t -> topicEntities.add(t.toTopicEntity()));
		topicService.addTopics(topicEntities);
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.PUT)
	public void updateTopic(@PathVariable("name") String name,
	        @RequestBody Topic topic) {
		logger.debug("update topic {}", topic);
		TopicEntity topicEntity = topic.toTopicEntity();

		topicService.updateTopic(topicEntity);
	}

	@RequestMapping(value = "/{name}", method = RequestMethod.DELETE)
	public void deleteTopic(@PathVariable("name") String name) {
		logger.debug("delete topic {}", name);
		topicService.deleteTopic(name);
	}

}